﻿using System;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Zoomit;

namespace DeepZoom.Samples.ZoomItBrowser
{
    public partial class MainWindow
    {
        DispatcherTimer _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.5), IsEnabled = false };

        public MainWindow()
        {
            InitializeComponent();
            Navigate();
        }

        private void NavigateClick(object sender, RoutedEventArgs e)
        {
            Navigate();
        }

        private void Navigate()
        {
            var uri = new Uri(Address.Text);
            Zoomit.BeginGetContentInfo(uri, ZoomitCallback, uri);
        }

        private void ZoomitCallback(IAsyncResult asyncResult)
        {
            var uri = asyncResult.AsyncState as Uri;

            base.Dispatcher.BeginInvoke(new Action(() =>
            {
                try
                {
                    LoadingMessage.Visibility = Visibility.Collapsed;

                    var content = Zoomit.EndGetContentInfo(asyncResult);
                    var dzi = content.Dzi;

                    if (content.Ready && dzi != null)
                    {
                        // Success
                        DeepZoomImage.Source = new DeepZoomImageTileSource(dzi.Uri);
                    }
                    else if (content.Failed)
                    {
                        // Failed
                        ShowMessage("{0} failed to convert.", uri);
                    }
                    else
                    {
                        // Loading
                        Retry(uri);
                        LoadingMessage.Text = string.Format("loading... {0}%", Math.Round(100 * content.Progress));
                        LoadingMessage.Visibility = Visibility.Visible;
                    }
                }
                catch (Exception e)
                {
                    ShowMessage(
                        "{0} was rejected! Error message:\n{1}",
                        uri, e.Message);
                }
            }));
        }

        private void Retry(Uri uri)
        {
            _timer.Tick += (s, e) =>
            {
                _timer.IsEnabled = false;
                Zoomit.BeginGetContentInfo(uri, ZoomitCallback, uri);
            };
            _timer.Start();
        }

        private void ShowMessage(string message, params object[] args)
        {
            MessageBox.Show(string.Format(message, args));
        }
    }
}
